#!/usr/bin/python
# -*- coding: UTF-8 -*-
import logging
import random

server_logger = logging.getLogger("server")
import time

from tbitem.util import maokoulingClass

from tbitem.util.itemTemplate import ContentFactory
from tbitem.util.qiboPOST import bokeePOST, ContentConfig
import os,django
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "shareAPI2020TB.settings")# project_name 项目名称
django.setup()

import json
import jsonpath
import requests

from tbitem import models
def getATitle():
    #从数据库中取出淘宝已经处理过爬取的链接
    querySetList = models.BBSContent.objects.filter(status=2).all()
    return querySetList



def stepTest():
    server_logger.error(f"step4-----Start")
    logging.info('ok')
    try:
        # 调用数据库账号设置：
        bokeeconfig_QuerySetList = models.QiBoAccount.objects.all()
        if not bokeeconfig_QuerySetList:
            server_logger.error(f"step4-----step4企博账号还没有配置呢，请速速配置----")
            return 'qibo账号还没有配置呢'
        else:
            bokeeAccount = bokeeconfig_QuerySetList[0]
            server_logger.error(f"step4-----运行账号：{bokeeAccount.username}----")

            querySetList = getATitle()
            if not querySetList:
                return 'BBSContent还没与数据'
            # print(querySet.keyword)  #关键词
            # print(querySet.tbid)  # 淘宝id  ->取商品图文，取tbkurl
            # print(querySet.contentWord)  #句子
            # for querySet in querySetList:
            querySet = querySetList[0]  #只发一次
            # 尝试取淘宝客推广链接
            TbIndex_Query = models.TbIndex.objects.filter(tbid=querySet.tbid).first()
            if not TbIndex_Query.tbkURL:  # 如果没有链接，就开始申请淘宝客链接
                logging.info("没有淘宝客链接，转换链接（店铺，item两个都要）")

                # id转链接
                abc = maokoulingClass.maokouling_ONE()
                abc.itemid = TbIndex_Query.tbid
                abc.userid = maokoulingClass.item_to_SELLID(abc)
                tbkUrl = maokoulingClass.tblink_get_gaoyong(abc)
                tbShopUrl = maokoulingClass.userid_to_shopTBK_link(abc)

                # 链接入库
                TbIndex_Query.tbkURL = tbkUrl
                TbIndex_Query.tbkShopURL = tbShopUrl
                TbIndex_Query.save()

            # 生成发帖模板
            TBimg_Query = models.TbIMG.objects.filter(tbimg_Index=TbIndex_Query).all()
            TBComment_Query = models.TbComment.objects.filter(tbComment_Index=TbIndex_Query).all()

            firstWord_Query = models.TbFirstWord.objects.order_by('?')[:1].first()  # @type:querySet
            lastWord_Query = models.TbLastWord.objects.order_by('?')[:1].first()   # @type:querySet
            if not firstWord_Query:
                firstWord = '买前必看！'
            else:
                firstWord = firstWord_Query.firstWord
            if not lastWord_Query:
                lastWord = '质量怎么样？'
            else:
                lastWord = lastWord_Query.lastWord
            """
            TbIndex_Query 实例   tbindex， /商品淘链接/店铺淘链接
            querySet    实例  BBSContent       /关键词/源标题/
            TBimg_Query  实例(多)  TbIMG       /商品的图片合集
            TBComment_Query  实例(多)  TbComment  商品的评论合集
            """
            print(TbIndex_Query)
            print(querySet)
            print(TBimg_Query)
            print(TBComment_Query)

            # 组合成文章 htmlContent
            htmlContent = ContentFactory(TbIndex_Query, querySet, TBimg_Query, TBComment_Query)
            print(htmlContent)

            # 发布内容如果发布成功，就更改tbindex表的状态为3
            if htmlContent == None:
                logging.info("组合文章出错")
                server_logger.error(f"step4-----组合文章出错")
            else:
                # 发布企博
                # '''3、发博客'''
                # # 调用企业博客发帖模块函数块需要的内容----START

                bokeeconfig = bokeeAccount
                bokeeconfig.title = f"{firstWord}{querySet.keyword}{lastWord}",
                bokeeconfig.content = htmlContent,

                # print("11111111111111111111111111111111111111111111111")
                # print(content)
                # print("11111111111111111111111111111111111111111111111")
                bokeeconfig.columnName = '值得买',  # 分类名字1
                bokeeconfig.addType = '值得买',  # 分类2
                bokeeconfig.tags = '',  # 标签
                bokeeconfig.brief = ""  # 内容摘要

                """发帖_Start"""
                postresult = bokeePOST(bokeeconfig)
                if postresult == True:
                    # 发帖成功
                    # # 调用企业博客发帖模块函数块需要的内容----END
                    querySet.status = 3
                    querySet.save()
                    time.sleep(50)
                    # cursor.execute(f'update JiSuBBS set 备用 = 3,生成评论内容 = {content}')
                else:
                    server_logger.error(f"step4-----帖子SUUCCESS----")
                    # break
                    # exit(code='帖子数量发够了,退出程序')
                server_logger.error(f"step4-----运行成功")
                time.sleep(5)
        return f'启动发帖，发贴账号是{bokeeAccount.username}'
    except Exception as e:
        server_logger.error(f"step4-----step4出错----{e}")
if __name__ == '__main__':
    # stepTest()  #取出一条 状态2的bbscontent数据，然后发企博,发布成功，设置 BBSContent 表状态为3（已成功发布）

    run_modelQuery = models.RunModel.objects.first()
    print(run_modelQuery.modelType)



